package com.msmall.community.user.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.model.OperationResult;
import com.msmall.base.pager.MatchType;
import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.base.util.DateUtil;
import com.msmall.community.money.model.Money;
import com.msmall.community.roster.service.RosterManager;
import com.msmall.community.score.model.Score;
import com.msmall.community.user.dao.UserDao;
import com.msmall.community.user.model.LoginInfo;
import com.msmall.community.user.model.UserInfo;
import com.msmall.community.user.model.UserProfile;
import com.msmall.community.user.model.UserSetting;
import com.msmall.community.user.service.UserManager;
import com.msmall.community.user.util.UserUtil;

public class UserManagerImpl extends BaseManagerImpl implements UserManager {

	private static final Log logger = LogFactory.getLog(UserManagerImpl.class);
	
	private UserDao userDao;
	
	private RosterManager rosterManager;
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setRosterManager(RosterManager rosterManager) {
		this.rosterManager = rosterManager;
	}
	/**
	 * 创建一个匿名账号,放入缓存,仅创建UserInfo的部分信息：userid username nickname
	 */
	public UserInfo createAnonymousAccount(Long userid, String username){
		UserInfo user = new UserInfo();
		user.setUserid(userid);
		user.setUsername(username);
		user.setNickname(username);
		CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USER_NAME2ID).put(username, userid);
		CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).put(userid, user);
		return user;
	}
	/**
	 * 删除创建的匿名账号；从缓存删除
	 */
	public void removeAnonymousAccount(Long userid){
		UserInfo user = (UserInfo) CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).get(userid);
		if(user != null){
			CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USER_NAME2ID).remove(user.getUsername());
			CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).remove(user.getUserid());
		}
	}
	public OperationResult authenticate(String username, String passwd) {
		OperationResult authResult = new OperationResult();
		UserInfo userInfo = getByUsername(username);
		if(userInfo == null){
			authResult.setCode(OperationResult.CODE_FAIL);
			authResult.setDesc("1");
		}else if(userInfo.getPassword().equals(passwd)){
			authResult.setCode(OperationResult.CODE_SUCCESS);
			authResult.setDesc("认证通过");
			authResult.setObj(userInfo);
		} else {
			authResult.setCode(OperationResult.CODE_FAIL);
			authResult.setDesc("2");
		}
		return authResult;
	}

	/**
	 * false:此用户不存在
	 */
	public boolean isUsernameExisted(String username) {
		UserInfo userInfo = getByUsername(username);
		if(userInfo == null)
			return false;
		return true;
	}
	/**
	 * 通过用户昵称查找用户
	 */
	public void getPagination(PaginationSupport page, String nickname){
		String queryString = "from UserInfo where nickname like '%" + nickname +"%'";
		page.setQueryString(queryString);
		getPagination(page);
	}
	
	/**
	 * 通过性别，年龄段查找用户
	 * agesmin <= agesmax
	 */
	public void getPagination(PaginationSupport page, Short gender, Integer agesmax, Integer agesmin){
		if(agesmax == null){
			agesmax = 0;
		}
		if(agesmin == null){
			agesmin = 0;
		}
		if(agesmin.compareTo(agesmax) > 0){
			int temp = agesmin;
			agesmin = agesmax;
			agesmax = temp;
		}
		String queryString = "from UserInfo where gender=" + gender 
		+" and birthday >='" + DateUtil.getBirthDayString(agesmax) + "'"
		+" and birthday <='" + DateUtil.getBirthDayString(agesmin) + "'";
		page.setQueryString(queryString);
		getPagination(page);
	}
	/**
	 * @param nickname
	 * @return
	 * @throws Exception 
	 */
	public List<UserInfo> getByNickname(String nickname){
		try{
			List list = userDao.getByProperty(UserInfo.class, "nickname", MatchType.LIKE, nickname);
			if(list == null || list.size() == 0)
				return null;
			return list;
		}catch(Exception e){
			log.error(e);
			return null;
		}
	}
	
	public boolean register(UserInfo userInfo) {
		try{
			if(isUsernameExisted(userInfo.getUsername())){
				return false;
			}
			userInfo.setCreateTime(new Date());
			userInfo.setVipLevel(ConstantDB.VIP_NORMAL_LEVELS);
			userInfo.setLoginCnt(1);
			userInfo.setLockStatus(ConstantDB.UNLOCK_STATUS);
			userInfo.setLevels(ConstantDB.LEVELS_INIT);
			userInfo.setAvatar(ConstantDB.AVATAR_DEFAULT);
			
			Score score = new Score();
			score.setLockStatus(ConstantDB.UNLOCK_STATUS);
			score.setScore(0L);
			score.setVisible(ConstantDB.VISIBLE);
			score.setUser(userInfo);
			
			Money money = new Money();
			money.setLockStatus(ConstantDB.UNLOCK_STATUS);
			money.setMoney(0F);
			money.setVisible(ConstantDB.VISIBLE);
			money.setUser(userInfo);
			
			userInfo.setScore(score);
			userInfo.setMoney(money);
			
			userDao.saveObject(userInfo);
			userInfo = this.getByUsername(userInfo.getUsername());
			
			UserProfile profile = new UserProfile();
			profile.setUserid(userInfo.getUserid());
			profile.setAlbumAmount(0);
			profile.setDiaryAmount(0);
			profile.setVisitAmount(0L);
			profile.setRosterAmount(0);
			profile.setTopicAmount(0);
			profile.setThreadAmount(0);
			userDao.saveObject(profile);
			
			/**
			 * 当新用户注册时，初始化此用户在论坛的基本信息
			 */
//			UserBbs ub = new UserBbs();
//			ub.setEliteAmount(0);
//			ub.setThreadAmount(0);
//			ub.setTopicAmount(0);
//			ub.setUserid(userInfo.getUserid());
//			userDao.saveObject(ub);
			
			rosterManager.getGroupFriend(userInfo.getUserid());
			rosterManager.getGroupStranger(userInfo.getUserid());
			rosterManager.getGroupBlacklist(userInfo.getUserid());
			rosterManager.getGroupForbidden(userInfo.getUserid());
			return true;
		}catch(Exception e){
			log.error(e);
			return false;
		}
	}

	/**
	 * 先从缓存获得
	 */
	public UserInfo getByUsername(String username) {
		UserInfo user = null;
		Long userid = (Long) CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USER_NAME2ID).get(username);
		if(userid == null){
			List list = userDao.getByProperty(UserInfo.class, "username", MatchType.EQ, username);
			if(list != null && list.size() > 0){
				user = (UserInfo) list.get(0);
				CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USER_NAME2ID).put(username, user.getUserid());
				CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).put(user.getUserid(), user);
			}
		}else{
			user = getByUserid(userid);
		}
		return user;
	}
	/**
	 * 先从缓存获得
	 */
	public UserInfo getByUserid(Long userid){
		UserInfo user = (UserInfo) CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).get(userid);
		if(user == null){
			user = (UserInfo) get(UserInfo.class, userid);
			CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USER_NAME2ID).put(user.getUsername(), user.getUserid());
			CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).put(user.getUserid(), user);
		}
		return user;
	}
	/**
	 * 先从缓存获得
	 */
	public UserProfile getProfileByUserid(Long userid){
		try{
			return userDao.loadProfileByUserid(userid);
		}catch(Exception e){
			log.error(e);
		}
		return null;
	}
	
	/**
	 * 更新缓存
	 */
	public UserInfo saveAvatar(File avatar,String filename, String uat, Long userid){
		try{
			String[] pathinfo = UserUtil.saveImage(avatar, filename, userid, uat);
			UserInfo user = getByUserid(userid);
			user.setAvatar(pathinfo[0]+pathinfo[1]);
			user = (UserInfo) userDao.saveObject(user);
			CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).put(userid, user);
			return user;
		}catch(Exception e){
			log.error(e);
		}
		return null;
	}
	/**
	 * 更新缓存
	 */
	public UserInfo saveUserInfo(UserInfo userInfo){
		userInfo.setModifyTime(new Date());
		userInfo = (UserInfo) userDao.saveObject(userInfo);
		CacheFactory.getInstance().getUserCache(Constants.CACHE_NAME_USERINFO).put(userInfo.getUserid(), userInfo);
		return userInfo;
	}
	
	/**
	 * 当用户退出时，修改退出时间
	 * @param userid
	 */
	public void updateLogoutInfo(Long userid){
		try{
			LoginInfo info = userDao.loadLastLoginInfo(userid);
			info.setLogoutTime(new Date());
			saveObject(info);
		}catch(Exception e){
			log.error(e);
		}
	}
	/**
	 * 添加登陆信息
	 */
	public void addLoginInfo(LoginInfo login){
		login.setLoginTime(new Date());
		saveObject(login);
	}
	
	/**
	 * 获得用户的所有设置信息等
	 * @param userid
	 * @return
	 */
	public List<UserSetting> getSettingByUserid(Long userid){
		try {
			return userDao.getSettingByUserid(userid);
		} catch (Exception e) {
			log.debug(e);
		}
		return null;
	}
	
	public UserSetting getSetting(Long settingid){
		return (UserSetting) userDao.get(UserSetting.class, settingid);
	}
	
	/**
	 * key : ConstantDB.USER_SETTING_KEY_
	 */
	public UserSetting getSetting(Long userid, String key){
		try {
			return userDao.getSetting(userid, key);
		} catch (Exception e) {
			log.debug(e);
		}
		return null;
	}
	
	public UserSetting saveSetting(Long userid, String key, String value){
		try{
			UserSetting s = new UserSetting();
			s.setPropertyKey(key);
			s.setUserid(userid);
			s.setPropertyValue(value);
			s = (UserSetting) userDao.saveObject(s);
			return s;
		}catch(Exception e){
			log.debug(e);
		}
		return null;
	}
	
	public void addEliteAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setEliteAmount(profile.getEliteAmount() + 1);
		userDao.saveObject(profile);
	}

	public void reduceEliteAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setEliteAmount(profile.getEliteAmount() - 1);
		userDao.saveObject(profile);
	}
	public void addThreadAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setThreadAmount(profile.getThreadAmount() + 1);
		userDao.saveObject(profile);
	}

	public void addTopicAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setTopicAmount(profile.getTopicAmount() + 1);
		userDao.saveObject(profile);
	}
	/**
	 * 添加用户的日记数量，每次加1
	 * @param userid
	 */
	public void addDiaryAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setDiaryAmount(profile.getDiaryAmount() + 1);
		userDao.saveObject(profile);
	}
	
	/**
	 * 添加用户的相册数量，每次加1
	 * @param userid
	 */
	public void addAlbumAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setAlbumAmount(profile.getAlbumAmount() + 1);
		userDao.saveObject(profile);
	}
	
	/**
	 * 添加用户的好友数量，每次加1
	 * @param userid
	 */
	public void addRosterAmount(Long userid) {
		UserProfile profile = getProfileByUserid(userid);
		profile.setRosterAmount(profile.getRosterAmount() + 1);
		userDao.saveObject(profile);
	}
	/**
	 * 添加用户的空间访问数量，每次加1
	 * @param userid
	 */
	public void addVisitAmount(Long userid){
		UserProfile profile = getProfileByUserid(userid);
		profile.setVisitAmount(profile.getVisitAmount() + 1);
		userDao.saveObject(profile);
	}
}
